

package com.maoshi.shop.user.platform.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.maoshi.shop.bean.model.Category;
import com.maoshi.shop.bean.model.SysConfig;
import com.maoshi.shop.bean.param.CategoryScoreConfigParam;
import com.maoshi.shop.bean.param.ScoreConfigParam;
import com.maoshi.shop.common.annotation.SysLog;
import com.maoshi.shop.common.config.Constant;
import com.maoshi.shop.common.util.Json;
import com.maoshi.shop.service.CategoryService;
import com.maoshi.shop.service.SysConfigService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 积分基本配置信息
 * @author lhd
 */
@RestController
@RequestMapping("/user/scoreConfig")
public class ScoreConfigController {

	@Autowired
	private SysConfigService sysConfigService;

	@Autowired
	private CategoryService categoryService;


	/**
	 * 获取配置信息
	 */
	@GetMapping("/info/{id}")
	@PreAuthorize("@pms.hasPermission('user:scoreSonfig:info')")
	public ResponseEntity<ScoreConfigParam> info(@PathVariable("id") String key){
		ScoreConfigParam scoreParamDb = sysConfigService.getSysConfigObject(key,ScoreConfigParam.class);
		if(Objects.isNull(scoreParamDb)){
			ScoreConfigParam scoreParam = new ScoreConfigParam();
			addCategoryConfig(scoreParam);
			return ResponseEntity.ok(scoreParam);
		}
		if(Objects.isNull(scoreParamDb) || CollectionUtils.isEmpty(scoreParamDb.getCategoryConfigs())){
			addCategoryConfig(scoreParamDb);
		}

		//判断分类数据是否正确
		List<Category> categoryList = categoryService.list(new LambdaQueryWrapper<Category>()
				.eq(Category::getParentId,Constant.CATEGORY_ID)
				.eq(Category::getShopId,Constant.PLATFORM_SHOP_ID)
		);
//		Map<Long, List<Category>> categoryMap = categoryList.stream().collect(Collectors.groupingBy(Category::getCategoryId));
//		更新数据并去除删除的数据
//		Iterator<CategoryScoreConfigParam> iterator = scoreParamDb.getCategoryConfigs().iterator();
//		while (iterator.hasNext()){
//			CategoryScoreConfigParam category = iterator.next();
//			List<Category> categories = categoryMap.get(category.getCategoryId());
//			if (Objects.isNull(categories)){
//				iterator.remove();
//			}else {
//				category.setCategoryName(category.getCategoryName());
//				categoryMap.remove(category.getCategoryId());
//			}
//		}
//		Set<Long> longs = categoryMap.keySet();
//		//写入新增的分类
//		for (Long catrgoryId:longs){
//			Category category = categoryMap.get(catrgoryId).get(0);
//			CategoryScoreConfigParam categoryScoreConfigParam = new CategoryScoreConfigParam();
//			categoryScoreConfigParam.setCategoryId(category.getCategoryId());
//			categoryScoreConfigParam.setCategoryName(category.getCategoryName());
//			categoryScoreConfigParam.setGetScoreLimit(1.00);
//			categoryScoreConfigParam.setUseScoreLimit(1.00);
//			scoreParamDb.getCategoryConfigs().add(categoryScoreConfigParam);
//		}

		if(scoreParamDb.getSignInScoreString() != null) {
			List<Integer> signScore = new ArrayList<>();
			String[] scores = scoreParamDb.getSignInScoreString().split(StrUtil.COMMA);
			for (String score : scores) {
				signScore.add(Integer.valueOf(score));
			}
			scoreParamDb.setSignInScore(signScore);
		}
//		scoreParamDb.setId(config.getId());
		return ResponseEntity.ok(scoreParamDb);
	}

	private void addCategoryConfig(ScoreConfigParam scoreParam) {
		List<CategoryScoreConfigParam> params = new ArrayList<>();
		List<Category> categories = categoryService.list(new LambdaQueryWrapper<Category>()
				.le(Category::getGrade, 1)
				.eq(Category::getShopId, Constant.PLATFORM_SHOP_ID)
				.eq(Category::getParentId,0)
				.orderByAsc(Category::getSeq));
		for (Category category : categories) {
			CategoryScoreConfigParam param = new CategoryScoreConfigParam();
			param.setCategoryId(category.getCategoryId());
			param.setCategoryName(category.getCategoryName());
			param.setGetScoreLimit(0.0);
			param.setUseScoreLimit(0.0);
			params.add(param);
		}
		scoreParam.setCategoryConfigs(params);
	}


	/**
	 * 保存配置
	 */
	@SysLog("保存配置")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('user:scoreSonfig:save')")
	public ResponseEntity<Void> save(@RequestBody @Valid ScoreConfigParam scoreConfigParam){
		sysConfigService.saveOrUpdateSysConfigService(scoreConfigParam,Constant.SCORE_CONFIG);
		return ResponseEntity.ok().build();
	}

	/**
	 * 修改配置
	 */
	@SysLog("修改配置")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('user:scoreSonfig:update')")
	public ResponseEntity<Void> update(@RequestBody @Valid ScoreConfigParam scoreConfigParam){
//		SysConfig config = new SysConfig();
//		List<Integer> signInScore = scoreConfigParam.getSignInScore();
//		if(CollectionUtils.isNotEmpty(signInScore)) {
//			StringBuilder signsString = new StringBuilder();
//			for (Integer score : signInScore) {
//				signsString.append(score).append(StrUtil.COMMA);
//			}
//			signsString.deleteCharAt(signsString.length() - 1);
//			scoreConfigParam.setSignInScoreString(signsString.toString());
//			scoreConfigParam.setSignInScore(null);
//		}
////		if(Objects.equals(scoreConfigParam.getDiscountRange(),0)){
////			scoreConfigParam.setCategoryConfigs(null);
////		}else{
////			scoreConfigParam.setDiscount(null);
////		}
//		config.setRemark("积分获取比例和积分抵现规则");
//		config.setId(scoreConfigParam.getId());
//		scoreConfigParam.setId(null);
//		String paramValue = Json.toJsonString(scoreConfigParam);
//		config.setParamValue(paramValue);
//		sysConfigService.updateById(config);
//		sysConfigService.removeSysConfig(Constant.SCORE_CONFIG);
		return ResponseEntity.ok().build();
	}


}
